package com.example.testcache1.utils;

import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.Log;

/**
 * 鍐呭瓨缂撳瓨锛屽寘鍚簡涓�骇璺熶簩绾х紦瀛�
 * 
 * @author bm
 */
public class MemoryCache {

	public final static long DEFAULT_CACHE_SIZE = Runtime.getRuntime().totalMemory() / 4;

	// 鏈�繎鏈�皯娣樻卑鍘熷垯
	private LruCache<String, Bitmap> mLruCache;
	private HashMap<String, SoftReference<Bitmap>> mSoftCache = new HashMap<String, SoftReference<Bitmap>>();

	public MemoryCache() {
		this((int) DEFAULT_CACHE_SIZE);
	}

	public MemoryCache(int maxSize) {
		mLruCache = new LruCache<String, Bitmap>(maxSize) {
			@Override
			protected int sizeOf(String key, Bitmap value) {
				// 璁＄畻鍑篵itmap鎵�崰鐢ㄥ唴瀛樼殑澶у皬
				return value.getRowBytes() * value.getHeight();
			}

			@Override
			protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
				super.entryRemoved(evicted, key, oldValue, newValue);

				// 褰撶紦瀛樺璞′粠涓�骇缂撳瓨涓绉婚櫎鐨勬椂鍊欙紝灏嗕粬鏀惧叆鍒颁簩绾х紦瀛樹腑
				SoftReference<Bitmap> soft = new SoftReference<Bitmap>(oldValue);
				mSoftCache.put(key, soft);
			}
		};
	}

	public void put(String key, Bitmap value) {
		mLruCache.put(key, value);
	}
 
	public Bitmap get(String key) {

		Bitmap bmp = null;

		// 鍏堜粠涓�骇缂撳啿涓壘
		bmp = mLruCache.get(key);

		// 涓�骇缂撳瓨娌℃湁鐨勮瘽
		if (bmp == null) {

			// 浠庝簩绾х紦瀛樹腑鍙�
			SoftReference<Bitmap> soft = mSoftCache.get(key);

			if (soft != null) {
				bmp = soft.get();

				if (bmp != null) {
					// 浜岀骇缂撳啿鍙栧緱鍒扮殑璇濆啀娆℃斁鍏ュ埌涓�骇缂撳瓨涓�
					mLruCache.put(key, bmp);
				}
			}
		}

		return bmp;
	}
}